/**
 * PluginClassLoader.java
 * 
 * FreeZzaph is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * FreeZzaph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.
 */
package freezzaph.classloader;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

public final class PluginClassLoader {

	private JarClassLoader jcl;
	private String[] className;
	private String pluginType;

	public PluginClassLoader(URI location) throws ClassNotFoundException {
		try {
			jcl = new JarClassLoader(new File(location).getCanonicalPath());
		} catch (IOException e) {
			throw new ClassNotFoundException("Could not load JAR");
		}

		try {
			String jarPath = location.toURL().toString();
			URL manifestUrl =
					new URL("jar:" + jarPath + "!/META-INF/MANIFEST.MF");
			Manifest manifest = new Manifest(manifestUrl.openStream());

			Attributes attr = manifest.getMainAttributes();
			
			Attributes.Name attrName = new Attributes.Name("Plugin-Type");
			if (attr.containsKey(attrName)) {
				pluginType = attr.getValue(attrName);
			}

			attrName = new Attributes.Name("Plugin-Class");
			if (attr.containsKey(attrName)) {
				String plugins = attr.getValue(attrName); 
				className = plugins.split("\\s*,\\s*");
			}

		} catch (IOException ioe) {
			throw new ClassNotFoundException("JAR does not contain plugin");
		}
	}

	public Class<?>[] loadPluginClass() {
		Class<?>[] pluginClasses = new Class<?>[className.length];
		for (int i = 0; i < className.length; i++) {
			try {
				pluginClasses[i] = jcl.loadClass(className[i]);
			} catch (ClassNotFoundException e) {
				// Leave the spot as null
			}
		}
		return pluginClasses;
	}

	public String getPluginType() {
		return pluginType;
	}

}
